﻿@page "/usercenter/{UserName?}"
@inject IJSRuntime  JSRuntime
@inject NavigationManager NavigationManager
@inject HttpClient HttpClient
@inject MessageService _message
@inject IConfiguration configure
@using Lemon.Blog.Enum

<div class="usef-menu">
    <div class="usef-menu-left">
        <span class="left-title">个人中心</span>
        @*<ul class="left-ul">
                <li>博客</li>
                <li>个人信息</li>
            </ul>*@
        <Menu Class="left-ul" DefaultSelectedKeys=@(new[] { "personal" }) OnMenuItemClicked="(item) => MenuKey = item.Key">
            <MenuItem Key="personal">个人信息</MenuItem>
            <MenuItem Key="blog">博    客</MenuItem>
        </Menu>
    </div>
    <div class="usef-menu-right">
        @if (MenuKey == "blog")
        {
            <div class="right-title">博客</div>
            <div>
                <iframe id="blogFrame" src="/userbloglist/@UserName" frameborder="0" scrolling="no" style="width:828px;min-height:890px;"></iframe>
            </div>
        }
        else if (MenuKey == "personal")
        {
            <div class="right-title">个人信息</div>
            <div class="set-headphoto">
                <div>
                    <Avatar Size="64" Src="@HeadPhoto" />
                </div>
                @if (IsSelf)
                {
                    <div style="color:#aaa;margin-left: 5px;">
                        @(string.IsNullOrEmpty(imageUrl) ? "当前头像" : "预览头像")
                    </div>
                    <div>
                        <Upload Action="@(APIUrl + "/api/blog/public-method/upload-file")"
                                Name="file"
                                Class="avatar-uploader"
                                ListType="picture-card"
                                ShowUploadList="false"
                                BeforeUpload="BeforeUpload"
                                OnChange="HandleChange"
                                Headers="@AuthHeader"
                                Data="@UploadDto">
                            @if (!string.IsNullOrWhiteSpace(imageUrl))
                            {
                                <img src="@imageUrl" alt="avatar" style="width: 100%" />
                            }
                            else
                            {
                                <div>
                                    <Icon Spin="loading" Type="@(loading ? "Loading" : "plus")"></Icon>
                                    <div className="ant-upload-text">上传头像</div>
                                </div>
                            }
                        </Upload>
                    </div>
                    <div>
                        <span style="color:#aaa">推荐大小180 * 180像素支持JPG、PNG格式，图片需小于2M</span>
                    </div>
                    <div class="update-head-button">
                        <Button OnClick=UpdateHeadPhoto Disabled="@(string.IsNullOrEmpty(imageUrl))">
                            更新头像
                        </Button>
                    </div>
                }
            </div>
            <div class="user-setting">
                @if (IsSelf)
                {
                    <Form Model="@UserInfoDto"
                          OnFinish="UpdateUserInfo">
                        <FormItem Class="nick-name" Label="昵称">
                            <Input @bind-Value="@context.Name" />
                        </FormItem>
                        <FormItem Class="user-name" Label="用户名">
                            <div style="color: #898989;"><span>@UserName</span></div>
                        </FormItem>
                        <FormItem Class="user-my-sign" Label="我的签名">
                            <TextArea @bind-Value="@context.Signature" />
                        </FormItem>
                        <FormItem Class="user-sex" Label="性别">
                            <RadioGroup @bind-Value="@context.Sex">
                                <Radio RadioButton Value="@(UserSexEnum.Man)">男</Radio>
                                <Radio RadioButton Value="@(UserSexEnum.Woman)">女</Radio>
                                <Radio RadioButton Value="@(UserSexEnum.Unknown)">保密</Radio>
                            </RadioGroup>
                        </FormItem>
                        <FormItem Label="出生日期">
                            <DatePicker @bind-Value="@context.DateOfBirth" />
                        </FormItem>

                        <FormItem Class="user-setting-submit">
                            <Button HtmlType="submit">
                                保存
                            </Button>
                        </FormItem>
                    </Form>
                }
                else
                {
                    <Form Model="@UserInfoDto"
                          OnFinish="UpdateUserInfo">
                        <FormItem Class="nick-name" Label="昵称">
                            <div style="color: #898989;"><span>@context.Name</span></div>
                        </FormItem>
                        <FormItem Class="user-name" Label="用户名">
                            <div style="color: #898989;"><span>@UserName</span></div>
                        </FormItem>
                        <FormItem Class="user-my-sign" Label="我的签名">
                            <div style="color: #898989;"><span>@context.Signature</span></div>
                        </FormItem>
                        <FormItem Class="user-sex" Label="性别">
                            <div style="color: #898989;"><span>@context.Sex.GetDescription()</span></div>
                        </FormItem>
                        <FormItem Label="出生日期">
                            <div style="color: #898989;"><span>@context.DateOfBirth.ToString("yyyy年MM月dd日")</span></div>
                        </FormItem>
                    </Form>
                }
            </div>
        }
    </div>
</div>

<style>
    .usef-menu {
        overflow-x: hidden;
        width: 980px;
        height: 100%;
        margin: 10px auto 100px;
        border: 1px solid #e1e2e5;
        box-shadow: 0 2px 4px rgb(0 0 0 / 14%);
        background: #fafafa;
        border-radius: 4px;
        padding: 0;
    }

    .usef-menu-left {
        float: left;
        width: 150px;
        height: 100%;
        overflow: hidden;
    }

    .usef-menu-right {
        float: left;
        width: 828px;
        border-left: 1px solid #ddd;
        background: #fff;
        min-height: 890px !important;
        height: 100%;
    }

    .left-title {
        display: block;
        width: 150px;
        height: 50px;
        text-align: center;
        line-height: 50px;
        font-size: 16px;
        color: #99a2aa;
        cursor: default;
        border-bottom: 1px solid #e1e2e5;
    }

    .left-ul {
        border-bottom: 1px solid #e1e2e5;
    }

        .left-ul li {
            width: 150px;
            height: 48px !important;
            line-height: 48px !important;
            padding-left: 43px !important;
            font-size: 15px;
            color: #222;
            margin: 0 !important;
        }

    .right-title {
        height: 35px;
        padding-left: 30px;
        border-bottom: 1px solid #ddd;
        margin: 15px 0 0 5px;
        color: #00a1d6;
        font-size: 15px;
        cursor: default;
    }

    .ant-menu-item-selected {
        background-color: #00a1d7 !important;
        color: #fff !important;
    }

    * {
        margin: 0;
        padding: 0;
    }

    .nick-name {
        width: 225px;
        height: 30px;
        margin-left: 28px;
    }

    .user-my-sign textarea {
        float: left;
        width: 618px;
        height: 88px !important;
        resize: none;
    }

    .user-setting {
        padding: 20px 20px;
    }

    .user-name {
        margin-left: 14px
    }

    .user-sex {
        margin-left: 28px;
    }

    .user-setting-submit {
        text-align: center
    }

        .user-setting-submit button {
            background: #00a1d6 !important;
            color: #fff;
            width: 110px;
            height: 36px;
        }

    .set-headphoto {
        margin: 20px 0 0 88px;
    }

    .avatar-uploader > .ant-upload {
        width: 128px;
        height: 128px;
        margin-top: 24px;
    }

    .update-head-button button {
        background: #00a1d6;
        color: #fff;
        width: 110px;
        height: 36px;
    }
</style>

@code {
    [Parameter]
    public string UserName { get; set; }
    public UserInfoDto UserInfo { get; set; }
    public string MenuKey { get; set; }
    public UpdateUserInfoDto UserInfoDto = new UpdateUserInfoDto();
    public bool loading = false;
    public Dictionary<string, string> AuthHeader { get; set; }
    public bool IsSelf { get; set; } = false;
    public string HeadPhoto { get; set; }
    public Dictionary<string, object> UploadDto = new Dictionary<string, object>()
    {
            {"FileType",0 }
        };

    public string imageUrl;
    public string APIUrl => configure.GetSection("API")["Url"];
    public string SelfUrl => configure.GetSection("App")["SelfUrl"];
    public string AuthUrl => configure.GetSection("AuthServer")["Authority"];

    protected override async Task OnInitializedAsync()
    {
        MenuKey = "personal";
        var userInfoJson = await JSRuntime.InvokeAsync<string>("localStorage.getItem", "userinfo");
        if (!string.IsNullOrEmpty(userInfoJson))//登录了
        {
            UserInfo = JsonSerializer.Deserialize<UserInfoDto>(userInfoJson);
            if (UserName == UserInfo?.UserName)//且是用户中心本人
            {
                IsSelf = true;
                UserName = UserInfo.UserName;
                UserInfoDto.Name = UserInfo.Name;
                UserInfoDto.Id = UserInfo.Id;
                UserInfoDto.Signature = UserInfo.Signature;
                UserInfoDto.Sex = UserInfo.Sex;
                UserInfoDto.DateOfBirth = UserInfo.DateOfBirth ?? new DateTime(1996, 1, 1);
                AuthHeader = new Dictionary<string, string>()
            {
                    { "Authorization", await JSRuntime.InvokeAsync<string>("localStorage.getItem", "Authorization")}
                };
            }
            else//查看别人信息
                await GetUserInfoAsync(UserName);
        }
        else//未登录
        {
            await GetUserInfoAsync(UserName);
            //跳转登录代码
            //var authUrl = AuthUrl + $"/connect/authorize?response_type=code&client_id=Blog_Blazor&redirect_uri={SelfUrl}/login-callback&scope=Blog";
            //NavigationManager.NavigateTo(authUrl);
        }
        await base.OnInitializedAsync();
    }

    /// <summary>
    /// 更改用户信息
    /// </summary>
    /// <param name="editContext"></param>
    /// <returns></returns>
    private async Task UpdateUserInfo(EditContext editContext)
    {
        string url = "/api/blog/my-account/user-info";
        StringContent content = new StringContent(JsonSerializer.Serialize(UserInfoDto), Encoding.UTF8, "application/json");
        var respone = await HttpClient.PutAsync(url, content);
        if (respone.IsSuccessStatusCode)
        {
            await _message.Success("保存成功");
            var res = await HttpClient.GetFromJsonAsync<UserInfoDto>("/api/blog/my-account/user-info");
            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "userinfo", JsonSerializer.Serialize(res));
        }
        else
            await _message.Error("保存失败");
    }

    bool BeforeUpload(UploadFileItem file)
    {
        var isJpgOrPng = file.Type == "image/jpeg" || file.Type == "image/png";
        if (!isJpgOrPng)
        {
            _message.Error("只支持jpg和png格式");
        }
        var isLt2M = file.Size / 1024 / 1024 < 2;
        if (!isLt2M)
        {
            _message.Error("请上传小于2M的图片");
        }
        return isJpgOrPng && isLt2M;
    }

    void HandleChange(UploadInfo fileinfo)
    {
        loading = fileinfo.File.State == UploadState.Uploading;
        Console.WriteLine(fileinfo.File.State);

        if (fileinfo.File.State == UploadState.Success)
        {
            imageUrl = fileinfo.File.Response;
            UserInfo.HeadPhoto = fileinfo.File.Response;
        }
        InvokeAsync(StateHasChanged);
    }

    /// <summary>
    /// 更新头像
    /// </summary>
    /// <returns></returns>
    public async Task UpdateHeadPhoto()
    {
        string url = $"/api/blog/my-account/update-head-photo?url={imageUrl}";
        var respone = await HttpClient.GetAsync(url);
        if (respone.IsSuccessStatusCode)
        {
            await _message.Success("头像更新成功");
            var res = await HttpClient.GetFromJsonAsync<UserInfoDto>("/api/blog/my-account/user-info");
            await JSRuntime.InvokeVoidAsync("localStorage.setItem", "userinfo", JsonSerializer.Serialize(res));
        }
        else
            await _message.Error("头像更新失败");
    }

    /// <summary>
    /// 根据username查询用户信息
    /// </summary>
    /// <param name="username"></param>
    /// <returns></returns>
    public async Task GetUserInfoAsync(string username)
    {
        var res = await HttpClient.GetAsync($"/api/blog/my-account/user-info-by-username?username={UserName}");
        var userinfo = await res.Content.ReadFromJsonAsync<UserInfoDto>();
        HeadPhoto = userinfo.HeadPhoto;
        UserInfoDto.Name = userinfo.Name;
        UserInfoDto.Id = userinfo.Id;
        UserInfoDto.Signature = userinfo.Signature;
        UserInfoDto.Sex = userinfo.Sex;
        UserInfoDto.DateOfBirth = userinfo.DateOfBirth ?? new DateTime(1996, 1, 1);
    }
}